#include "stdafx.h"
#include "net/ICMPClient.hpp"
#include "net/ICMPSocket.hpp"
#include <sstream>

NET_NAMESPACE_BEGIN

CICMPClient::CICMPClient(CIPAddress::Family family) : m_family(family)
{
}

CICMPClient::~CICMPClient()
{
}

int CICMPClient::ping(const std::string& address, int repeat) const
{
	if (repeat <= 0) return 0;

	CSocketAddress addr(address, 0);
	return ping(addr, repeat);
}

int CICMPClient::ping(CSocketAddress& address, int repeat) const
{
	if (repeat <= 0) return 0;

	CICMPSocket icmpSocket(m_family);
	CSocketAddress returnAddress;

	CICMPEventArgs eventArgs(address, repeat, icmpSocket.dataSize(), icmpSocket.ttl());
	pingBegin.notify(this, eventArgs);

	for (int i = 0; i < repeat; ++i)
	{
		icmpSocket.sendTo(address);
		++eventArgs;

		try
		{
			int t = icmpSocket.receiveFrom(returnAddress);
			eventArgs.setReplyTime(i, t);
			pingReply.notify(this, eventArgs);
		}
		catch (TimeoutException&)
		{
			std::ostringstream os;
			os << address.host().toString() << ": Request timed out.";
			eventArgs.setError(i, os.str());
			pingError.notify(this, eventArgs);
			continue;
		}
		catch (ICMPException& ex)
		{
			std::ostringstream os;
			os << address.host().toString() << ": " << ex.what();
			eventArgs.setError(i, os.str());
			pingError.notify(this, eventArgs);
			continue;
		}
		catch (CException& ex)
		{
			std::ostringstream os;
			os << ex.displayText();
			eventArgs.setError(i, os.str());
			pingError.notify(this, eventArgs);
			continue;
		}
	}
	pingEnd.notify(this, eventArgs);
	return eventArgs.received();
}

int CICMPClient::pingIPv4(const std::string& address, int repeat)
{
	if (repeat <= 0) return 0;

	CSocketAddress a(address, 0);
	return ping(a, CIPAddress::IPv4, repeat);
}

int CICMPClient::ping(CSocketAddress& address, CIPAddress::Family family, int repeat)
{
	if (repeat <= 0) return 0;

	CICMPSocket icmpSocket(family);
	CSocketAddress returnAddress;
	int received = 0;

	for (int i = 0; i < repeat; ++i)
	{
		icmpSocket.sendTo(address);
		try
		{
			icmpSocket.receiveFrom(returnAddress);
			++received;
		}
		catch (TimeoutException&)
		{
		}
		catch (ICMPException&)
		{
		}
	}
	return received;
}


NET_NAMESPACE_END
